// 百度地图API功能
var map;
// 创建地址解析器实例
var myGeo;

var minZoom = 12;
var maxZoom = 18;

function fshowMap(idname,type,address_id,lat_id,lng_id){
	if(typeof BMap=="object"){
		baiduMapInit(idname,type,address_id,lat_id,lng_id);
		$('#'+address_id).change( function() {
			addressToLngLat($('#'+address_id).val(),lat_id,lng_id);
		});
		
	}
}

function baiduMapInit(mapId,type,address_id,lat_id,lng_id){
	map = new BMap.Map(mapId);
	var point = new BMap.Point((type==0?116.331398:$("#"+lng_id).val()),(type==0?39.897445:$("#"+lat_id).val()));
	map.centerAndZoom(point,(type==0?minZoom:maxZoom));
	myGeo = new BMap.Geocoder();
	
	if(type==1){
		var marker = new BMap.Marker(point);
		map.addOverlay(marker);
		
		var addr = "当前位置:" + $('#'+address_id).val()+ "<br/>纬度:" + $("#"+lat_id).val() + ", " + "经度:" + $("#"+lng_id).val();
		var label = new BMap.Label(addr,{offset:new BMap.Size(10,-34)});
		label.setStyle({
			'max-width':'none',
			'padding':'2px'
		});
		marker.setLabel(label);
	}
	
	map.addEventListener("click", function(e){
		var pt = e.point;
		map.clearOverlays();
		var marker = new BMap.Marker(pt);
		map.addOverlay(marker);
		
		myGeo.getLocation(pt, function(rs){
			var addComp = rs.addressComponents;
			var address = (addComp.province==null?'':addComp.province) + (addComp.city==null?'':addComp.city) + (addComp.district==null?'':addComp.district) + (addComp.street==null?'':addComp.street) + (addComp.streetNumber==null?'':addComp.streetNumber);
			$("#"+address_id).val(address);
			$("#"+lng_id).val(pt.lng);
			$("#"+lat_id).val(pt.lat);
			var addr = "当前位置：" + addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber+ "<br/>纬度: " + pt.lat + ", " + "经度：" + pt.lng;
			
			var label = new BMap.Label(addr,{offset:new BMap.Size(10,-34)});
			marker.setLabel(label);
		});
	});
}

function addressToLngLat(address,lat_id,lng_id){
	// 将地址解析结果显示在地图上,并调整地图视野
	myGeo.getPoint(address, function(point){
		if (point) {
			map.clearOverlays();
			$('#'+lat_id).val(point.lat);
			$('#'+lng_id).val(point.lng);
			var marker = new BMap.Marker(point);
			map.addOverlay(marker);
			map.centerAndZoom(point, maxZoom);
			var addr = "当前位置：" + address+ "<br/>纬度: " + point.lat + ", " + "经度：" + point.lng;
			var label = new BMap.Label(addr,{offset:new BMap.Size(10,-34)});
			marker.setLabel(label);
		}else{
			alert("您选择地址没有解析到结果!");
		}
	}, "北京市");
}